﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.IO;
using Lite.ExcelLibrary.SpreadSheet;
using System.Collections;
using System.Xml.Linq;
using System.Runtime.InteropServices.Automation;
using System.Collections.ObjectModel;
using System.Windows.Browser;
using AdvancedStandingAndScholarship.ASASService;
using AdvancedStandingAndScholarship.Views;
using System.IO.IsolatedStorage;

namespace AdvancedStandingAndScholarship
{
    public partial class AddPage : Page
    {
        public AddPage()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }

        private void rbn_graduatedYes_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            gridGraduated.Visibility = Visibility.Visible;
            gridNotGraduated.Visibility = Visibility.Collapsed;
        }

        private void rbn_graduatedNo_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            gridGraduated.Visibility = Visibility.Collapsed;
            gridNotGraduated.Visibility = Visibility.Visible;
        }


        private void btnAddManual_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

            // TODO: Add event handler implementation here.
            gridManual.Visibility = Visibility.Visible;
            gridUpload.Visibility = Visibility.Collapsed;

            lblAddUpload.Foreground = new SolidColorBrush(Color.FromArgb(163, 163, 163, 163));
            lblAddManual.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));

        }

        void client_addNewStudentCompleted(object sender, addNewStudentCompletedEventArgs e)
        {
            if (e.Error == null && e.Result != null)
            {
                List<ASASService.Student> studentList = (List<ASASService.Student>)e.Result;
                if (studentList[0].Student_id == null)
                {
                    //add fail
                    MessageBox.Show("Failed to add student! Student exist!");
                }
                else
                {
                    //add success
                    AddSuccessPage.studentList = studentList;
                    NavigationService.Navigate(new Uri("/AddSuccessPage", UriKind.RelativeOrAbsolute));
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }

        private void btnAddUpload_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //// TODO: Add event handler implementation here.
            //gridManual.Visibility = Visibility.Collapsed;
            //gridUpload.Visibility = Visibility.Visible;



            //lblAddManual.Foreground = new SolidColorBrush(Color.FromArgb(163, 163, 163, 163));
            //lblAddUpload.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));

            CookieHelper.SetCookie("Authenticated", "y");
            IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
            CookieHelper.SetCookie("selectedSchool", userSettings["selectedSchool"].ToString());
            try
            {
                System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("/Browse.aspx", UriKind.RelativeOrAbsolute));
            }
            catch (Exception)
            {
                try
                {
                    System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("/Browse.aspx", UriKind.RelativeOrAbsolute));
                }
                catch (Exception)
                {

                }
            }
        }

        private void btnBack_Add_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // TODO: Add event handler implementation here.
            if (NavigationService.CanGoBack)
                NavigationService.GoBack();
            else
            {

                NavigationService.Navigate(new Uri("/AddPageSelectSchool", UriKind.Relative));
            }
        }


        private void btnBrowse_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            CookieHelper.SetCookie("Authenticated", "y");
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("/Browse.aspx", UriKind.RelativeOrAbsolute));




            //http://www.silverlightshow.net/items/An-Excel-file-Viewer-in-Silverlight-4.aspx
            //To access file system we need to use Silverlight file dialogs
            //OpenFileDialog oFile = new OpenFileDialog();
            //// .xls filter specified to select only .xls file.
            //oFile.Filter = "Excel (*.xlsx)|*.xlsx";
            //if (oFile.ShowDialog() == true)
            //{
            //    // Get the stream of the selected file
            //    FileStream fs = oFile.File.OpenRead();
            //    #region method 2 Buggy
            //    //XLSXReader asd = new XLSXReader(oFile.File);
            //    //asd.GetFilename();
            //    //List<string> subItems = asd.GetListSubItems();
            //    //IEnumerable<IDictionary>  result = asd.GetData(asd.GetFilename());

            //    #endregion

            //    #region method 1 works for xls only
            //    //// Simply call the Open method of Workbook and you are done
            //    //Workbook book = Workbook.Open(fs);
            //    //// All of the worksheet will be populated with data 
            //    //// currently we will read only first for this sample
            //    //Worksheet sheet = book.Worksheets[0];
            //    ///// itrating through worksheet object to get values
            //    ///// Worksheet.Cells.FirstRowIndex tells the First row index of data
            //    ///// Worksheet.Cells.LastRowIndex tells the last of data
            //    ///// Worksheet.Cells.FirstColIndex has first index of column value
            //    ///// Worksheet.Cells.LastColIndex has last index of column
            //    ///// So itrating using these properties will traverse all data of the sheet
            //    ///// 
            //    //for (int i = sheet.Cells.FirstRowIndex; i < sheet.Cells.LastRowIndex; i++)
            //    //{
            //    //    for (int j = sheet.Cells.FirstColIndex; j < sheet.Cells.LastColIndex; j++)
            //    //    {
            //    //        /// value of each cell is separated by a coma 
            //    //        this.textBox1.Text += sheet.Cells[i, j].StringValue;
            //    //        this.textBox1.Text += ",";
            //    //    }
            //    //    // New row will be displayed on next line
            //    //    this.textBox1.Text += Environment.NewLine;
            //    //}

            //    #endregion


            //}



        }

        private void btnSubmitManualAdd_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            bool gotError = false;
            ASASService.Student student = new Student();
            List<ASASService.Student> studentList = new List<ASASService.Student>();

            student.Name = tbxName.Text;
            student.NRIC1 = tbxNRIC.Text;
            student.Passport_no = tbxPassportNumber.Text;

            if (rbnMale.IsChecked == true)
            {
                student.Gender = "m";
            }
            else if (rbnFemale.IsChecked == true)
            {
                student.Gender = "f";
            }
            try
            {
                student.Dob = Convert.ToDateTime(tbxDOB.Text);
            }
            catch (Exception)
            {
                gotError = true;
            }
            student.Diploma = tbxDiploma.Text;
            student.Diploma_graduated_year = tbxPolyGraduationYear.Text;
            student.Matric_year = tbxMatricYear.Text;
            student.Uni_faculty = tbxUniFaculty.Text;
            student.Uni_degree = tbxUniDegree.Text;
            student.Poly_school = tbxSchool.Text;


            //to be change later

            IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
            student.Uni_name = userSettings["selectedSchool"].ToString();

            if (rbn_graduatedNo.IsChecked == true)
            {
                student.Student_type = "matriculated";
                student.Ddp_cdp_course = tbxDDPCDP.Text;
                student.Scholarship = tbxScholarshipN.Text;
                student.Uni_application_year = tbxUniApplicationYear.Text;

            }
            else if (rbn_graduatedYes.IsChecked == true)
            {
                student.Student_type = "graduated";
                student.Uni_graduated_year = tbxGraduationAcademicYear.Text;
                student.Class_of_honours = tbxClassOfHonours.Text;
                student.Scholarship = tbxScholarshipsG.Text;
                student.Awards_dean_list = tbxPrizes.Text;
            }
            //if no error
            if (gotError == false)
            {
                studentList.Add(student);
                ASASServiceClient client = new ASASServiceClient();
                client.addNewStudentCompleted += new EventHandler<addNewStudentCompletedEventArgs>(client_addNewStudentCompleted);
                client.addNewStudentAsync(studentList, "szesze@live.com");
            }

        }





    }
}
